<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">员工管理</h1>
      <n-button type="primary" @click="handleAdd">
        <template #icon>
          <n-icon><AddOutline /></n-icon>
        </template>
        新增员工
      </n-button>
    </div>
    
    <!-- 搜索栏 -->
    <n-card style="margin-bottom: 16px;">
      <n-space>
        <n-input 
          v-model:value="searchParams.keyword" 
          placeholder="搜索姓名或账号" 
          clearable 
          style="width: 200px;"
        />
        <n-select 
          v-model:value="searchParams.role" 
          placeholder="角色" 
          clearable 
          :options="roleOptions"
          style="width: 150px;"
        />
        <n-select 
          v-model:value="searchParams.status" 
          placeholder="状态" 
          clearable 
          :options="statusOptions"
          style="width: 150px;"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
        <n-button @click="handleReset">重置</n-button>
      </n-space>
    </n-card>
    
    <!-- 表格 -->
    <div class="table-wrapper">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        @update:page="handlePageChange"
      />
    </div>
    
    <!-- 新增/编辑对话框 -->
    <n-modal v-model:show="showModal" preset="dialog" :title="modalTitle" style="width: 600px;">
      <n-form ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="100">
        <n-form-item label="姓名" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入姓名" />
        </n-form-item>
        <n-form-item label="账号" path="account">
          <n-input v-model:value="formData.account" placeholder="请输入账号" />
        </n-form-item>
        <n-form-item label="密码" :path="formData.id ? '' : 'password'">
          <n-input 
            v-model:value="formData.password" 
            type="password" 
            :placeholder="formData.id ? '不填写则不修改' : '请输入密码（默认123456）'" 
          />
        </n-form-item>
        <n-form-item label="角色" path="role">
          <n-select v-model:value="formData.role" :options="roleOptions" placeholder="请选择角色" />
        </n-form-item>
        <n-form-item label="电话" path="phone">
          <n-input v-model:value="formData.phone" placeholder="请输入电话" />
        </n-form-item>
        <n-form-item label="入职日期" path="hireDate">
          <n-date-picker v-model:value="formData.hireDate" type="date" placeholder="请选择入职日期" style="width: 100%;" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-radio :value="1">在职</n-radio>
            <n-radio :value="0">离职</n-radio>
          </n-radio-group>
        </n-form-item>
      </n-form>
      
      <template #action>
        <n-space>
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, reactive } from 'vue'
import { getEmployeePage, addEmployee, updateEmployee, deleteEmployee } from '@/api/employee'
import { 
  NButton, NIcon, NCard, NSpace, NInput, NSelect, NDataTable, NTag, NModal,
  NForm, NFormItem, NDatePicker, NRadioGroup, NRadio, useMessage, useDialog
} from 'naive-ui'
import { AddOutline, CreateOutline, TrashOutline } from '@vicons/ionicons5'

const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const tableData = ref([])
const showModal = ref(false)
const modalTitle = ref('新增员工')
const formRef = ref(null)

const searchParams = reactive({
  keyword: '',
  role: null,
  status: null
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

const roleOptions = [
  { label: '店长', value: 'MANAGER' },
  { label: '店员', value: 'STAFF' }
]

const statusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 0 }
]

const formData = ref({
  id: null,
  name: '',
  account: '',
  password: '',
  role: null,
  phone: '',
  hireDate: null,
  status: 1
})

const rules = {
  name: { required: true, message: '请输入姓名', trigger: 'blur' },
  account: { required: true, message: '请输入账号', trigger: 'blur' },
  password: { required: true, message: '请输入密码', trigger: 'blur' },
  role: { required: true, message: '请选择角色', trigger: 'change' },
  hireDate: { required: true, type: 'number', message: '请选择入职日期', trigger: 'change' }
}

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '姓名', key: 'name' },
  { title: '账号', key: 'account' },
  { 
    title: '角色', 
    key: 'role',
    render: (row) => {
      const type = row.role === 'MANAGER' ? 'warning' : 'info'
      return h(NTag, { type }, { default: () => row.role === 'MANAGER' ? '店长' : '店员' })
    }
  },
  { title: '电话', key: 'phone' },
  { title: '入职日期', key: 'hireDate' },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'default' }, { 
        default: () => row.status === 1 ? '在职' : '离职' 
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, {
            size: 'small',
            onClick: () => handleEdit(row)
          }, { 
            default: () => '编辑',
            icon: () => h(NIcon, {}, { default: () => h(CreateOutline) })
          }),
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleDelete(row)
          }, { 
            default: () => '删除',
            icon: () => h(NIcon, {}, { default: () => h(TrashOutline) })
          })
        ]
      })
    }
  }
]

async function loadData() {
  try {
    loading.value = true
    const res = await getEmployeePage({
      page: pagination.page,
      size: pagination.pageSize,
      ...searchParams
    })
    tableData.value = res.data.records
    pagination.itemCount = res.data.total
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  loadData()
}

function handleReset() {
  searchParams.keyword = ''
  searchParams.role = null
  searchParams.status = null
  pagination.page = 1
  loadData()
}

function handlePageChange(page) {
  pagination.page = page
  loadData()
}

function handleAdd() {
  modalTitle.value = '新增员工'
  formData.value = {
    id: null,
    name: '',
    account: '',
    password: '',
    role: null,
    phone: '',
    hireDate: new Date().getTime(),
    status: 1
  }
  showModal.value = true
}

function handleEdit(row) {
  modalTitle.value = '编辑员工'
  formData.value = {
    ...row,
    password: '',
    hireDate: new Date(row.hireDate).getTime()
  }
  showModal.value = true
}

function handleDelete(row) {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除员工「${row.name}」吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteEmployee(row.id)
        message.success('删除成功')
        loadData()
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    
    const data = {
      ...formData.value,
      hireDate: new Date(formData.value.hireDate).toISOString().slice(0, 10)
    }
    
    if (formData.value.id) {
      await updateEmployee(data)
      message.success('更新成功')
    } else {
      await addEmployee(data)
      message.success('新增成功')
    }
    
    showModal.value = false
    loadData()
  } catch (error) {
    if (error.message) {
      message.error(error.message)
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

